import {Component, ComponentProps, Computed, Hook, Mut, VueComponent} from "vue3-oop";
import {NButton, NCard, NCollapse, NDrawer, NDrawerContent, NForm, NScrollbar, NSpace, NTag, NTabs, NTabPane} from "naive-ui";
import styles from "./index.module.scss";
import { nicon } from "@/utils/IconUtil";
import BpmnModeler from "@/module/main/other/BpmnTestView/BpmnModeler";
import {BasePanel,MessagePanel,ConditionPanel,ExtensionsPanel,FormPanel,InstancesPanel,
  ListenersPanel,OtherPanel,TaskListenersPanel,TaskPanel} from './panels'

interface IProps {
  drawerTo: string,
  bpmnModeler: BpmnModeler
}
@Component()
export default class Index extends VueComponent<IProps> {
  static defaultProps: ComponentProps<IProps> = {
    drawerTo: {default:'drawerToId'},
    bpmnModeler: {default:{} as any}
  }

  constructor() {
    super()
  }

  @Mut() private state = {
    id:'',
    name:'',
    type:'',

    showPanel: false,
    showBase: false,
    showMessage: false,
    showCondition: false,
    showForm: false,
    showTask: false,
    showInstances: false,
    showListeners: false,
    showTaskListeners: false,
    showExtensions: false,
    showOther: false
  }

  @Mut() selectedElement?:any;
  @Mut() businessObject?:any;

  @Computed() get selectedTypeZhCN(){
    return this.typeZhCN(this.state.type);
  }

  private typeZhCN=(type:string)=>{
    const typeMap = {
      'Process': '工作流',
      'StartEvent': '开始事件',
      'EndEvent': '结束事件',
      'IntermediateThrowEvent': '中间/边界事件',
      'SequenceFlow': '流转链接',
      'ExclusiveGateway': '互斥网关',
      'ParallelGateway': '并行网关',
      'InclusiveGateway': '相容网关',
      'ComplexGateway': '复杂网关',
      'EventBasedGateway': '事件网关',
      'Task': '任务',
      'UserTask': '用户任务',
      'SendTask': '发送任务',
      'ReceiveTask': '接收任务',
      'ManualTask': '手工任务',
      'BusinessRuleTask': '业务规则任务',
      'ServiceTask': '服务任务',
      'ScriptTask': '脚本任务',
      'CallActivity': '调用活动',
      'SubProcess': '子流程',
      'DataObjectReference': '数据对象',
      'DataStoreReference': '数据存储',
      'Participant': '池/参与者',
      'Group': '分组'
    } as any;
    return typeMap[type]?typeMap[type]:type;
  }

  /** 切换打开关闭属性面板 */
  public toggleShowPanel=()=>{
    this.state.showPanel = !this.state.showPanel;
  }

  /**
   * 处理点击选择图形
   */
  private handleSeletedElementChanged=()=>{
    const selectedElement = this.props.bpmnModeler.getSelectedElement();
    if (!selectedElement) return;
    // console.log("handleSeletedElementChanged",selectedElement)

    this.selectedElement = selectedElement;
    this.businessObject = JSON.parse(JSON.stringify(selectedElement.businessObject));
    this.state.id = this.businessObject.id;
    this.state.name = this.businessObject.name;
    this.state.type = selectedElement.type.split(":")[1] || "";

    // base
    this.state.showBase = true;
    // message
    this.state.showMessage = (this.state.type === "Process");
    // condition
    this.state.showCondition = (this.state.type === "SequenceFlow" && selectedElement.source && selectedElement.source.type.indexOf("StartEvent") === -1);
    // form
    this.state.showForm = (this.state.type === "UserTask" || this.state.type === "StartEvent");
    // task
    this.state.showTask = (this.state.type.includes("Task"));
    // instances
    this.state.showInstances = (this.state.type.includes("Task"));
    // listeners
    this.state.showListeners = true;
    // taskListeners
    this.state.showTaskListeners = (this.state.type === "UserTask");
    // extensions
    this.state.showExtensions = true;
    // other
    this.state.showOther = true;
  }

  @Hook("Mounted")
  private onMounted(){
    // 监听导入完成事件
    this.props.bpmnModeler.onImportDone((e:any)=>{
      this.handleSeletedElementChanged();
    })
    // 监听选择事件
    this.props.bpmnModeler.onSelectionChanged((e:any)=>{
      this.handleSeletedElementChanged();
    })
    // 监听元素修改事件
    this.props.bpmnModeler.onElementChanged((e:any)=>{
      if (e.element && e.element.id === this.selectedElement.id) {
        // 某些操作(修改"默认流转路径")会修改多个元素，更新表单的元素要与原选中的元素一致
        this.handleSeletedElementChanged();
      }
    })
    // 监听
    this.props.bpmnModeler.onCommandStackChanged((e:any)=>{
      // console.log(e)
    })
  }

  render(){
    const propsFormToggleTitle = (this.state.name && this.state.name.length>0)?this.state.name:this.state.id;
    const CmpProps = {bpmnModeler:this.props.bpmnModeler,elementId:this.state.id,elementName:this.state.name,elementType:this.state.type};
    return (
      <>
        <NButton
          class={[styles.bpmn_props_button]}
          size={"small"}
          onClick={this.toggleShowPanel}
        >{`属性面板:${this.selectedTypeZhCN} ${propsFormToggleTitle}`}</NButton>
        <NDrawer
          class={[styles.bpmn_props_drawer]}
          to={this.props.drawerTo}
          placement={'bottom'}
          resizable={true}
          trapFocus={false}
          showMask={false}
          show={this.state.showPanel}
          defaultHeight={300}
        >
          <NDrawerContent>
            <NCard>
              {{
                header:()=>(
                  <NSpace><NTag bordered={false} size={'large'} style={{fontSize:'18px'}} color={{color:'whitesmoke'}}>
                    {{ avatar: nicon("IosSettings"), default: ()=>`属性面板:${this.selectedTypeZhCN} ${propsFormToggleTitle}` }}
                  </NTag></NSpace>
                ),
                'header-extra':()=>(
                  <NSpace size={'small'}>
                    <NButton size={'small'} type={"primary"} onClick={this.toggleShowPanel}>关闭面板</NButton>
                  </NSpace>
                ),
                default:()=>(
                  <NTabs type="line" animated class={[styles.bpmn_props_tabs]}>
                    { this.state.showBase && <NTabPane name={BasePanel.tabKey} tab={BasePanel.tabName}><NScrollbar><BasePanel {...CmpProps} /></NScrollbar></NTabPane> }
                    { this.state.showMessage && <NTabPane name={MessagePanel.tabKey} tab={MessagePanel.tabName}><NScrollbar><MessagePanel {...CmpProps} /></NScrollbar></NTabPane> }
                    { this.state.showCondition && <NTabPane name={ConditionPanel.tabKey} tab={ConditionPanel.tabName}><NScrollbar><ConditionPanel {...CmpProps} /></NScrollbar></NTabPane> }
                    { this.state.showForm && <NTabPane name={FormPanel.tabKey} tab={FormPanel.tabName}><NScrollbar><FormPanel {...CmpProps} /></NScrollbar></NTabPane> }
                    { this.state.showTask && <NTabPane name={TaskPanel.tabKey} tab={TaskPanel.tabName}><NScrollbar><TaskPanel {...CmpProps} /></NScrollbar></NTabPane> }
                    { this.state.showInstances && <NTabPane name={InstancesPanel.tabKey} tab={InstancesPanel.tabName}><NScrollbar><InstancesPanel {...CmpProps} /></NScrollbar></NTabPane> }
                    { this.state.showListeners && <NTabPane name={ListenersPanel.tabKey} tab={ListenersPanel.tabName}><NScrollbar><ListenersPanel {...CmpProps} /></NScrollbar></NTabPane> }
                    { this.state.showTaskListeners && <NTabPane name={TaskListenersPanel.tabKey} tab={TaskListenersPanel.tabName}><NScrollbar><TaskListenersPanel {...CmpProps} /></NScrollbar></NTabPane> }
                    { this.state.showExtensions && <NTabPane name={ExtensionsPanel.tabKey} tab={ExtensionsPanel.tabName}><NScrollbar><ExtensionsPanel {...CmpProps} /></NScrollbar></NTabPane> }
                    { this.state.showOther && <NTabPane name={OtherPanel.tabKey} tab={OtherPanel.tabName}><NScrollbar><OtherPanel {...CmpProps} /></NScrollbar></NTabPane> }
                  </NTabs>
                )
              }}
            </NCard>
          </NDrawerContent>
        </NDrawer>
      </>
    )
  }
}